package com.sun.filter;

import com.sun.bean.Login;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        //1:将父类转为子类
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //2:获取请求的路径
        String url = req.getRequestURI();

        // /day_16/login.jsp
        int num1 = url.lastIndexOf("login.jsp");
        int num2 = url.lastIndexOf("code");
        int num3 = url.lastIndexOf("user");

        //2:获取session
        HttpSession session = req.getSession();
        //3:从session中获取user对象
        Login login = (Login) session.getAttribute("lg");
        //1 对路径放行  login.jsp  code(验证码),  登录后台 user
        if(num1 != -1 || num2 != -1 || num3 != -1){
            filterChain.doFilter(req, resp);
            return;
        }
        //4:对user进行非空判断
        if (login != null) {
            filterChain.doFilter(req, resp);
        } else {
            //跳转到登录页面 重定向
            resp.sendRedirect("login.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
